/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DialogDocumentoVehiculo.java
 *
 * Created on 20/02/2011, 10:19:13 PM
 */

package com.catosist.run.application.vehiculo.documents;

import com.catosist.run.business.gestorDocumentosVehiculo.GestorDocumentosVehiculo;
import com.catosist.run.services.DocvehiDTO;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.Format;
import java.util.*;
import javax.swing.JComboBox;
import ca.odell.glazedlists.swing.AutoCompleteSupport;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.TextFilterator;
import ca.odell.glazedlists.matchers.TextMatcherEditor;
import java.awt.event.ContainerListener;
import java.util.Iterator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
import javax.swing.DefaultComboBoxModel;

/**
 *
 * @author igorov
 */
public class DialogDocumentoVehiculo extends javax.swing.JDialog {

    /** Creates new form DialogDocumentoVehiculo */
    public DialogDocumentoVehiculo(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public DialogDocumentoVehiculo(java.awt.Frame parent, boolean modal,
            int vehiculoId, int id, GestorDocumentosVehiculo gestorDocumentosVehiculo) {
        
        super(parent, modal);
        
        initComponents();
        this.gestorDocumentosVehiculo = gestorDocumentosVehiculo;
        this.vehiculoId = vehiculoId;
        this.id = id;
     
        refresh();

//        mapPosiblesIds = new HashMap<Integer, Integer>();


        this.posibles_nombre = gestorDocumentosVehiculo.getAllByNombre();
        this.posibles_agente = gestorDocumentosVehiculo.getAllByAgente();

        Url[] URLS = new Url[posibles_nombre.size()];
        Url[] URLS2 = new Url[posibles_agente.size()];

        for (int i = 0; i < posibles_nombre.size(); i++) {
            DocvehiDTO docvehiDTO = posibles_nombre.get(i);
//            mapPosiblesIds.put(docvehiDTO.getId(), i);
            
            URLS[i] = new Url(docvehiDTO.getNombre());
//            URLS2[i] = new Url(docvehiDTO.getAgente());
        }

        for (int i = 0; i < posibles_agente.size(); i++) {
            DocvehiDTO docvehiDTO = posibles_agente.get(i);
//            mapPosiblesIds.put(docvehiDTO.getId(), i);

//            URLS[i] = new Url(docvehiDTO.getNombre());
            URLS2[i] = new Url(docvehiDTO.getAgente());
        }

        final EventList<Url> urls = GlazedLists.eventList(Arrays.asList(URLS));
        final EventList<Url> urls2 = GlazedLists.eventList(Arrays.asList(URLS2));
        AutoCompleteSupport support = AutoCompleteSupport.install(cmbNombre, urls, new URLTextFilterator(), new UrlFormat());
        AutoCompleteSupport support2 = AutoCompleteSupport.install(cmbAgente, urls2, new URLTextFilterator(), new UrlFormat());
        support.setFilterMode(TextMatcherEditor.CONTAINS);
        support2.setFilterMode(TextMatcherEditor.CONTAINS);

        if (this.id > 0) {
            System.out.println("Conastructor");
            DocvehiDTO docvehiDTO = gestorDocumentosVehiculo.getById(id, vehiculoId);

            

//            System.out.println("Tratando de extraer con " + id+"valor: "+vehiculoId);
//            System.out.println("Nombre: "+docvehiDTO.getNombre());
//            System.out.println("Agente: "+docvehiDTO.getAgente());
//            this.txtNombre.setText(docvehiDTO.getNombre());
            int indice = 0;
            
            for (int i = 0; i < posibles_nombre.size(); i++) {
                DocvehiDTO tmp = posibles_nombre.get(i);
                String nombre = tmp.getNombre();
                System.out.println("Nombre: "+nombre);
                if (nombre.compareTo(docvehiDTO.getNombre()) == 0) {
                    indice = i;
                }
            }
            this.cmbNombre.setSelectedIndex(indice);
//            this.cmbNombre.setSelectedIndex(mapPosiblesIds.get(id));

            for (int i = 0; i < posibles_agente.size(); i++) {
                DocvehiDTO tmp = posibles_agente.get(i);
                String agente = tmp.getAgente();
                System.out.println("Nombre: "+agente);
                if (agente.compareTo(docvehiDTO.getAgente()) == 0) {
                    indice = i;
                }
            }
            this.cmbAgente.setSelectedIndex(indice);


            this.txtNumero.setText(docvehiDTO.getNumero());
            this.dtcFin.setDate(docvehiDTO.getFfin());
            this.dtcInicio.setDate(docvehiDTO.getFinicio());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtNumero = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        dtcInicio = new com.toedter.calendar.JDateChooser();
        dtcFin = new com.toedter.calendar.JDateChooser();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        cmbNombre = new javax.swing.JComboBox();
        cmbAgente = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.catosist.run.application.desktopapplication.DesktopApplication.class).getContext().getResourceMap(DialogDocumentoVehiculo.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        txtNumero.setName("txtNumero"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        dtcInicio.setName("dtcInicio"); // NOI18N

        dtcFin.setName("dtcFin"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        btnAceptar.setText(resourceMap.getString("btnAceptar.text")); // NOI18N
        btnAceptar.setName("btnAceptar"); // NOI18N
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setText(resourceMap.getString("btnCancelar.text")); // NOI18N
        btnCancelar.setName("btnCancelar"); // NOI18N
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        cmbNombre.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbNombre.setName("cmbNombre"); // NOI18N

        cmbAgente.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbAgente.setName("cmbAgente"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGap(71, 71, 71)
                                .addComponent(jLabel5))
                            .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel1))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(cmbNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(dtcFin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(dtcInicio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(cmbAgente, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(56, 56, 56)
                        .addComponent(btnAceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancelar)))
                .addContainerGap(47, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cmbNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(dtcInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(dtcFin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cmbAgente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAceptar)
                    .addComponent(btnCancelar))
                .addContainerGap(45, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed

        String nombreDocumento = ((Url)this.cmbNombre.getSelectedItem()).getLocation();
        String agenteDocumento = ((Url)this.cmbAgente.getSelectedItem()).getLocation();
        DocvehiDTO docvehiDTO = new DocvehiDTO();
        docvehiDTO.setAgente(agenteDocumento);
        docvehiDTO.setFfin(this.dtcFin.getDate());
        docvehiDTO.setFinicio(this.dtcInicio.getDate());
        docvehiDTO.setNombre(nombreDocumento);
        docvehiDTO.setNumero(this.txtNumero.getText());
        docvehiDTO.setVehiculoId(this.vehiculoId);
        docvehiDTO.setId(this.id);
        gestorDocumentosVehiculo.saveOrUpdate(docvehiDTO);
        this.setVisible(false);
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.setVisible(false);
}//GEN-LAST:event_btnCancelarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                DialogDocumentoVehiculo dialog = new DialogDocumentoVehiculo(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    private void refresh() {
        List<DocvehiDTO> docvehiDTOs = gestorDocumentosVehiculo.getAll();
        DefaultComboBoxModel model = new DefaultComboBoxModel();
   
        for (Iterator<DocvehiDTO> it = docvehiDTOs.iterator(); it.hasNext();) {
            DocvehiDTO docvehiDTO = it.next();
            model.addElement("Item");
        }
//        this.cmbDescripcionTipo.setModel(model);
//        if (this.id > 0) {
//            System.out.println("Conastructor");
//            DocvehiDTO docvehiDTO = gestorDocumentosVehiculo.getById(id, vehiculoId);
//
//            this.txtAgente.setText(docvehiDTO.getAgente());
//
//            System.out.println("Tratando de extraer con " + id+"valor: "+mapPosiblesIds.get(id));
////            this.txtNombre.setText(docvehiDTO.getNombre());
//            this.cmbNombre.setSelectedIndex(mapPosiblesIds.get(id));
//            this.txtNumero.setText(docvehiDTO.getNumero());
//            this.dtcFin.setDate(docvehiDTO.getFfin());
//            this.dtcInicio.setDate(docvehiDTO.getFinicio());
//        }
    }

    public void iniciar(){
        ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
        gestorDocumentosVehiculo = (GestorDocumentosVehiculo) ctx.getBean("gestorDocumentosVehiculo");
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JComboBox cmbAgente;
    private javax.swing.JComboBox cmbNombre;
    private com.toedter.calendar.JDateChooser dtcFin;
    private com.toedter.calendar.JDateChooser dtcInicio;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField txtNumero;
    // End of variables declaration//GEN-END:variables
    private GestorDocumentosVehiculo gestorDocumentosVehiculo;
    private int vehiculoId;
    private int id;
//    HashMap<Integer, Integer> mapPosiblesIds;
//    HashMap<Integer, Integer> mapPosiblesIdsAgentes;
    private List<DocvehiDTO> posibles_nombre;
    private List<DocvehiDTO> posibles_agente;
    private ApplicationContext ctx;

    public static final class Url {

        private final String location;

        public Url(String location) {
            this.location = location;
        }

        public String getLocation() {
            return location;
        }
    }

    private static final class URLTextFilterator implements TextFilterator<Url> {
        public void getFilterStrings(List<String> baseList, Url element) {
            final String location = element.getLocation();
            baseList.add(location);

            if (location.startsWith("http://"))
                baseList.add(location.substring(7));
            if (location.startsWith("http://www."))
                baseList.add(location.substring(11));
        }
    }

    private static final class UrlFormat extends Format {
        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
            if (obj != null)
                toAppendTo.append(((Url) obj).getLocation());
            return toAppendTo;
        }

        public Object parseObject(String source, ParsePosition pos) {
            return new Url(source);
        }
    }
}
